import express, { Request, Response, Router } from 'express';
import { PrismaClient } from '@prisma/client';
import { adminAuthMiddleware } from '../../middleware/adminAuth';
import { ApiResponse } from '../../utils/response';
import { rewardCalculationService } from '../../services/rewardCalculationService';

const router: Router = express.Router();
const prisma = new PrismaClient();

// 手动触发计算当日收益
router.post('/calculate-daily-rewards', adminAuthMiddleware, async (req: Request, res: Response): Promise<void> => {
  try {
    await rewardCalculationService.calculateDailyRewards();
    res.json(ApiResponse.success(null, '당일 수익 계산이 완료되었습니다.'));
  } catch (error) {
    console.error('당일 수익 계산 실패:', error);
    res.status(500).json(ApiResponse.error('당일 수익 계산에 실패했습니다.'));
  }
});

// 手动触发发放收益
router.post('/distribute-rewards', adminAuthMiddleware, async (req: Request, res: Response): Promise<void> => {
  try {
    await rewardCalculationService.distributeRewards();
    res.json(ApiResponse.success(null, '수익 배분이 완료되었습니다.'));
  } catch (error) {
    console.error('수익 발방 실패:', error);
    res.status(500).json(ApiResponse.error('수익 배분에 실패했습니다.'));
  }
});

// 强制发放（忽略时间限制，用于测试）
router.post('/force-distribute/:userId', adminAuthMiddleware, async (req: Request, res: Response): Promise<void> => {
  try {
    const { userId } = req.params;

    // 将nextDistributionAt设置为过去时间
    await prisma.userStaking.update({
      where: { userId: Number(userId) },
      data: {
        nextDistributionAt: new Date(Date.now() - 1000) // 1秒前
      }
    });

    // 执行发放
    await rewardCalculationService.distributeRewards();

    res.json(ApiResponse.success(null, '강제 지급이 완료되었습니다.'));
  } catch (error) {
    console.error('强制发放失败:', error);
    res.status(500).json(ApiResponse.error('강제 지급에 실패했습니다.'));
  }
});

// 查看用户质押详情
router.get('/user-staking/:userId', adminAuthMiddleware, async (req: Request, res: Response): Promise<void> => {
  try {
    const { userId } = req.params;

    const staking = await prisma.userStaking.findUnique({
      where: { userId: Number(userId) },
      include: {
        user: {
          select: {
            id: true,
            name: true,
            idNumber: true
          }
        }
      }
    });

    if (!staking) {
      res.status(404).json(ApiResponse.error('사용자의 스테이킹 기록이 없습니다.'));
      return;
    }

    const data = {
      ...staking,
      stakedAmount: Number(staking.stakedAmount),
      lockedAmount: Number(staking.lockedAmount),
      totalRewardsNear: Number(staking.totalRewardsNear),
      dailyRewardRate: Number(staking.dailyRewardRate),
      currentDailyReward: Number(staking.currentDailyReward),
      dailyRewardDistributed: Number(staking.dailyRewardDistributed)
    };

    res.json(ApiResponse.success(data));
  } catch (error) {
    console.error('사용자 스테이킹 조회 실패:', error);
    res.status(500).json(ApiResponse.error('사용자 스테이킹 조회에 실패했습니다.'));
  }
});

// 查看用户的收益发放记录
router.get('/staking-rewards/:userId', adminAuthMiddleware, async (req: Request, res: Response): Promise<void> => {
  try {
    const { userId } = req.params;
    const { limit = 20 } = req.query;

    const rewards = await prisma.stakingReward.findMany({
      where: { userId: Number(userId) },
      orderBy: { createdAt: 'desc' },
      take: Number(limit),
      select: {
        id: true,
        amount: true,
        txHash: true,
        createdAt: true
      }
    });

    const data = rewards.map(r => ({
      ...r,
      amount: Number(r.amount)
    }));

    res.json(ApiResponse.success(data));
  } catch (error) {
    console.error('수익 기록 조회 실패:', error);
    res.status(500).json(ApiResponse.error('수익 기록 조회에 실패했습니다.'));
  }
});

export default router;
